# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
import pymysql
from open_api import OpenAPI
from util import operate_mysql
from concurrent.futures import ThreadPoolExecutor


def fetch_customer_case_ids(task_id):
    try:
        with pymysql.connect(
            host="172.18.160.133",
            user="root",
            password="x3V4MD9AxaK7qFVD",
            db="yicall_1000",
            charset="utf8",
        ) as conn:
            with conn.cursor() as cursor:
                sql = "SELECT customer_case_id FROM b_1000_callout_session_shd_1 WHERE task_id=%s;"
                cursor.execute(sql, (task_id,))
                return cursor.fetchall()
    except pymysql.MySQLError as e:
        print(f"Database error: {e}")
        return []


def mark_sessions_finish(open_api, case_ids, task_id):

    def mark_single_session(case_id):
        try:
            open_api.mark_session_finish(case_id, inner_task_id=task_id)
        except Exception as e:
            print(f"Failed to mark session finish for case_id {case_id}: {e}")

    with ThreadPoolExecutor(max_workers=10) as executor:
        executor.map(mark_single_session, case_ids)


if __name__ == "__main__":
    task_id = 73
    result = fetch_customer_case_ids(task_id)
    if result:
        open_api = OpenAPI(token="16385000", ip="172.18.160.131")
        case_ids = [x[0] for x in result]
        mark_sessions_finish(open_api, case_ids, task_id)
